<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Git仓库管理工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        h1 {
            color: #333;
            text-align: center;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input[type="text"], input[type="password"], select {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-sizing: border-box;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 12px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            width: 100%;
            font-size: 16px;
            margin-bottom: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 5px;
            display: none;
        }
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
            margin-top: 30px;
        }
        .hidden {
            display: none;
        }
        .checkbox-group {
            display: flex;
            align-items: center;
        }
        .checkbox-group input[type="checkbox"] {
            width: auto;
            margin-right: 10px;
        }
        .branch-btn {
            background-color: #28a745;
        }
        .branch-btn:hover {
            background-color: #218838;
        }
        .build-btn {
            background-color: #ffc107;
            color: #212529;
        }
        .build-btn:hover {
            background-color: #e0a800;
        }
        .loading {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid #007bff;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
            vertical-align: middle;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .log-container {
            background-color: #000;
            color: #00ff00;
            padding: 15px;
            border-radius: 5px;
            font-family: monospace;
            max-height: 300px;
            overflow-y: auto;
            margin-top: 20px;
            display: none;
        }
        .process-step {
            margin: 5px 0;
            padding: 5px;
            border-left: 3px solid #007bff;
            background-color: #f8f9fa;
        }
        .process-step.completed {
            border-left-color: #28a745;
        }
        .process-step.error {
            border-left-color: #dc3545;
        }
        /* Jenkins风格的阶段展示 */
        .pipeline-stages {
            display: flex;
            justify-content: space-between;
            margin: 20px 0;
            position: relative;
        }
        .pipeline-stages::before {
            content: '';
            position: absolute;
            top: 20px;
            left: 0;
            right: 0;
            height: 2px;
            background-color: #ccc;
            z-index: 1;
        }
        .stage {
            text-align: center;
            position: relative;
            z-index: 2;
            flex: 1;
        }
        .stage-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background-color: #ccc;
            margin: 0 auto 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
        }
        .stage.pending .stage-icon {
            background-color: #ccc;
        }
        .stage.running .stage-icon {
            background-color: #007bff;
            animation: pulse 1.5s infinite;
        }
        .stage.success .stage-icon {
            background-color: #28a745;
        }
        .stage.failed .stage-icon {
            background-color: #dc3545;
        }
        .stage-name {
            font-size: 12px;
            word-break: break-all;
        }
        @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.5; }
            100% { opacity: 1; }
        }
        /* 构建控制按钮 */
        .build-controls {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }
        .build-controls button {
            flex: 1;
        }
        .next-stage-btn {
            background-color: #28a745;
        }
        .next-stage-btn:hover {
            background-color: #218838;
        }
        .pause-execution {
            background-color: #ffc107;
            color: #212529;
        }
        .pause-execution:hover {
            background-color: #e0a800;
        }
        .stage-detail {
            margin-top: 10px;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 5px;
            font-size: 14px;
        }
        /* 自动执行状态显示 */
        .auto-status {
            display: flex;
            align-items: center;
            margin: 10px 0;
            padding: 5px;
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Git仓库管理工具</h1>
        
        <div class="form-group">
            <label for="operation">操作类型:</label>
            <select id="operation" onchange="toggleOperation()" style="width: 100%; padding: 10px;">
                <option value="clone">克隆仓库</option>
                <option value="pull">更新仓库</option>
            </select>
        </div>
        
        <div id="clone-form">
            <div class="form-group">
                <label for="repo_url">仓库URL:</label>
                <input type="text" id="repo_url" placeholder="例如: http://192.168.1.153:3000/tongyu.frontend/Asst-Manager.git" value="http://192.168.1.153:3000/tongyu.frontend/Asst-Manager.git">
            </div>
            
            <div class="form-group">
                <button id="fetch-branches-btn" class="branch-btn" onclick="fetchBranches()">
                    <span id="fetch-branches-text">获取分支列表</span>
                </button>
            </div>
            
            <div class="form-group">
                <label for="branch">分支:</label>
                <select id="branch" disabled>
                    <option value="main">main (默认)</option>
                </select>
            </div>
        </div>
        
        <div id="pull-form" class="hidden">
            <div class="form-group">
                <p>将从默认仓库路径更新代码</p>
            </div>
        </div>
        
        <div class="form-group">
            <label for="token">访问令牌:</label>
            <input type="password" id="token" placeholder="请输入您的Git访问令牌" value="32821a75cfbe7fdc896cb08818944934d6a5e296">
        </div>
        
        <div class="form-group">
            <label for="target_subpath">构建目标子路径 (相对于dist目录):</label>
            <input type="text" id="target_subpath" placeholder="例如: h5 (留空则使用默认路径)">
        </div>
        
        <div class="form-group checkbox-group">
            <input type="checkbox" id="build_after_operation" checked>
            <label for="build_after_operation">操作完成后构建项目</label>
        </div>
        
        <button onclick="performAction()">执行操作</button>
        <button class="build-btn" id="build-btn" onclick="initBuildProject()">初始化构建项目</button>
        
        <!-- Jenkins风格的阶段展示 -->
        <div id="pipeline-stages" class="pipeline-stages hidden">
            <!-- 阶段将通过JavaScript动态生成 -->
        </div>
        
        <!-- 当前阶段详情 -->
        <div id="stage-detail" class="stage-detail hidden">
            <div class="auto-status">
                <span>▶ 自动执行已启动</span>
            </div>
            <div id="stage-detail-content"></div>
            <div class="build-controls">
                <button id="pause-btn" class="pause-execution" onclick="toggleAutoExecution()">暂停自动执行</button>
                <button onclick="resetBuildProcess()">重置构建</button>
            </div>
        </div>
        
        <div id="result" class="result"></div>
        
        <div id="log-container" class="log-container"></div>
        
        <div class="info">
            <h3>获取访问令牌的常见方法：</h3>
            <p><strong>🏢 GitLab (如 http://192.168.1.153:3000):</strong></p>
            <ol>
                <li>登录后点击右上角头像</li>
                <li>选择 "Edit profile" 或 "设置"</li>
                <li>左侧菜单选择 "Access Tokens"</li>
                <li>点击 "New personal access token"</li>
                <li>设置名称和权限，然后创建</li>
            </ol>
            
            <p><strong>🐙 GitHub:</strong></p>
            <ol>
                <li>Settings → Developer settings → Personal access tokens</li>
                <li>选择 "Tokens (classic)" 或 "Fine-grained tokens"</li>
                <li>点击 "Generate new token"</li>
            </ol>
            
            <p><strong>🌐 Gitea:</strong></p>
            <ol>
                <li>Settings → Applications</li>
                <li>在 "Personal Access Tokens" 部分操作</li>
            </ol>
            
            <p><strong>🔐 令牌权限建议：</strong></p>
            <ul>
                <li>read_repository: 只读权限（拉取代码）</li>
                <li>write_repository: 读写权限（推送代码）</li>
            </ul>
        </div>
    </div>

    <script>
        // 全局变量
        let currentPipelineId = null;
        let stageCount = 0;
        let autoExecution = true; // 默认启用自动执行
        let autoExecutionPaused = false; // 自动执行暂停标志
        
        // 页面加载完成后自动获取分支信息
        window.onload = async function() {
            try {
                // 设置默认仓库URL
                document.getElementById('repo_url').value = 'http://192.168.1.153:3000/tongyu.frontend/Asst-Manager.git';
                // 设置默认访问令牌
                document.getElementById('token').value = '32821a75cfbe7fdc896cb08818944934d6a5e296';
                // 自动获取分支信息
                await fetchBranches();
            } catch (error) {
                console.error('初始化失败:', error);
            }
        };
        
        function toggleOperation() {
            const operation = document.getElementById('operation').value;
            const cloneForm = document.getElementById('clone-form');
            const pullForm = document.getElementById('pull-form');
            
            if (operation === 'clone') {
                cloneForm.classList.remove('hidden');
                pullForm.classList.add('hidden');
            } else {
                cloneForm.classList.add('hidden');
                pullForm.classList.remove('hidden');
            }
        }
        
        // 获取分支列表
        async function fetchBranches() {
            const repoUrl = document.getElementById('repo_url').value;
            const token = document.getElementById('token').value;
            const branchSelect = document.getElementById('branch');
            const fetchBtn = document.getElementById('fetch-branches-btn');
            const fetchText = document.getElementById('fetch-branches-text');
            
            if (!repoUrl) {
                showMessage('请先填写仓库URL', 'error');
                return;
            }
            
            if (!token) {
                showMessage('请先填写访问令牌', 'error');
                return;
            }
            
            // 显示加载状态
            fetchText.innerHTML = '<span class="loading"></span>正在获取分支...';
            fetchBtn.disabled = true;
            
            try {
                const response = await fetch('/api/branches', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        repo_url: repoUrl,
                        token: token
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 清空现有选项
                    branchSelect.innerHTML = '';
                    
                    // 添加获取到的分支选项
                    data.branches.forEach(branch => {
                        const option = document.createElement('option');
                        option.value = branch;
                        option.textContent = branch;
                        branchSelect.appendChild(option);
                    });
                    
                    // 如果没有分支，添加默认选项
                    if (data.branches.length === 0) {
                        const option = document.createElement('option');
                        option.value = 'main';
                        option.textContent = 'main (默认)';
                        branchSelect.appendChild(option);
                    }
                    
                    // 启用分支选择下拉框
                    branchSelect.disabled = false;
                    showMessage(`成功获取到 ${data.branches.length} 个分支`, 'success');
                } else {
                    showMessage('获取分支列表失败: ' + data.message, 'error');
                }
            } catch (error) {
                showMessage('请求失败: ' + error.message, 'error');
            } finally {
                // 恢复按钮状态
                fetchText.textContent = '获取分支列表';
                fetchBtn.disabled = false;
            }
        }
        
        async function performAction() {
            const operation = document.getElementById('operation').value;
            const token = document.getElementById('token').value;
            const branch = document.getElementById('branch').value || 'main';
            const buildAfterOperation = document.getElementById('build_after_operation').checked;
            const targetSubpath = document.getElementById('target_subpath').value;
            const resultDiv = document.getElementById('result');
            const logContainer = document.getElementById('log-container');
            const pipelineStages = document.getElementById('pipeline-stages');
            const stageDetail = document.getElementById('stage-detail');
            
            // 重置构建显示
            resetBuildDisplay();
            resultDiv.style.display = 'none';
            logContainer.style.display = 'none';
            logContainer.innerHTML = '';
            
            if (!token) {
                showMessage('请提供访问令牌', 'error');
                return;
            }
            
            let response;
            
            try {
                if (operation === 'clone') {
                    const repoUrl = document.getElementById('repo_url').value;
                    
                    if (!repoUrl) {
                        showMessage('请填写仓库URL', 'error');
                        return;
                    }
                    
                    response = await fetch('/api/clone', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            repo_url: repoUrl,
                            token: token,
                            branch: branch,
                            build_after_clone: buildAfterOperation,
                            target_subpath: targetSubpath
                        })
                    });
                } else {
                    response = await fetch('/api/pull', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            token: token,
                            build_after_pull: buildAfterOperation,
                            target_subpath: targetSubpath
                        })
                    });
                }
                
                const data = await response.json();
                
                if (data.success) {
                    if (data.pipeline_id) {
                        // 如果返回了流水线ID，说明需要分步构建
                        currentPipelineId = data.pipeline_id;
                        stageCount = data.stage_count;
                        initPipelineDisplay(stageCount);
                        pipelineStages.classList.remove('hidden');
                        stageDetail.classList.remove('hidden');
                        document.getElementById('stage-detail-content').innerHTML = 
                            `<strong>下一步:</strong> ${data.next_stage}<br><strong>状态:</strong> 已准备`;
                        
                        // 默认自动执行
                        if (autoExecution && !autoExecutionPaused) {
                            await executeNextStage();
                        }
                    } else {
                        // 没有流水线ID，说明操作完成但不需要构建
                        pipelineStages.classList.add('hidden');
                        stageDetail.classList.add('hidden');
                    }
                    
                    showMessage(data.message + (data.local_path ? `<br>路径: ${data.local_path}` : ''), 'success');
                    if (data.logs) {
                        showLogs(data.logs);
                    }
                } else {
                    showMessage('操作失败: ' + data.message, 'error');
                    if (data.logs) {
                        showLogs(data.logs);
                    }
                }
            } catch (error) {
                showMessage('请求失败: ' + error.message, 'error');
            }
        }
        
        // 初始化构建项目
        async function initBuildProject() {
            const targetSubpath = document.getElementById('target_subpath').value;
            const resultDiv = document.getElementById('result');
            const logContainer = document.getElementById('log-container');
            const pipelineStages = document.getElementById('pipeline-stages');
            const stageDetail = document.getElementById('stage-detail');
            
            // 重置构建显示
            resetBuildDisplay();
            resultDiv.style.display = 'none';
            logContainer.style.display = 'none';
            logContainer.innerHTML = '';
            
            try {
                const response = await fetch('/api/build/init', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        target_subpath: targetSubpath
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    currentPipelineId = data.pipeline_id;
                    stageCount = data.stage_count;
                    initPipelineDisplay(stageCount);
                    pipelineStages.classList.remove('hidden');
                    stageDetail.classList.remove('hidden');
                    document.getElementById('stage-detail-content').innerHTML = 
                        `<strong>下一步:</strong> ${data.next_stage}<br><strong>状态:</strong> 已准备`;
                    
                    // 默认自动执行
                    if (autoExecution && !autoExecutionPaused) {
                        await executeNextStage();
                    }
                    
                    showMessage(data.message, 'success');
                    if (data.logs) {
                        showLogs(data.logs);
                    }
                } else {
                    showMessage('初始化失败: ' + data.message, 'error');
                    if (data.logs) {
                        showLogs(data.logs);
                    }
                }
            } catch (error) {
                showMessage('请求失败: ' + error.message, 'error');
            }
        }
        
        // 执行下一步构建
        async function executeNextStage() {
            if (!currentPipelineId) {
                showMessage('没有正在进行的构建流水线', 'error');
                return;
            }
            
            const pauseBtn = document.getElementById('pause-btn');
            const originalBtnText = pauseBtn.innerHTML;
            pauseBtn.disabled = true;
            pauseBtn.innerHTML = '<span class="loading"></span>执行中...';
            
            try {
                const response = await fetch('/api/build/execute_stage', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        pipeline_id: currentPipelineId
                    })
                });
                
                const data = await response.json();
                
                if (data.success) {
                    // 更新阶段显示
                    updateStageDisplay(data.stage_info);
                    
                    if (data.pipeline_completed) {
                        // 构建完成
                        currentPipelineId = null;
                        document.getElementById('stage-detail-content').innerHTML = 
                            `<strong>状态:</strong> ${data.stage_success ? '构建完成' : '构建失败'}<br>${data.message}`;
                        pauseBtn.classList.add('hidden');
                    } else {
                        // 还有下一步
                        currentPipelineId = data.pipeline_id;
                        document.getElementById('stage-detail-content').innerHTML = 
                            `<strong>下一步:</strong> ${data.stage_info.next_stage}<br><strong>状态:</strong> 已完成 ${data.stage_info.name}`;
                        
                        // 默认自动执行下一步（如果当前阶段成功）
                        if (autoExecution && !autoExecutionPaused && data.stage_success) {
                            setTimeout(executeNextStage, 1000); // 延迟1秒后继续执行
                        }
                    }
                    
                    if (data.logs) {
                        showLogs(data.logs);
                    }
                } else {
                    showMessage('执行失败: ' + data.message, 'error');
                    currentPipelineId = null;
                }
            } catch (error) {
                showMessage('请求失败: ' + error.message, 'error');
                currentPipelineId = null;
            } finally {
                pauseBtn.disabled = false;
                pauseBtn.innerHTML = originalBtnText;
                if (!currentPipelineId) {
                    pauseBtn.classList.add('hidden');
                }
            }
        }
        
        // 切换自动执行状态（暂停/继续）
        function toggleAutoExecution() {
            autoExecutionPaused = !autoExecutionPaused;
            const pauseBtn = document.getElementById('pause-btn');
            if (autoExecutionPaused) {
                pauseBtn.textContent = '继续自动执行';
                pauseBtn.classList.remove('pause-execution');
                pauseBtn.classList.add('next-stage-btn');
            } else {
                pauseBtn.textContent = '暂停自动执行';
                pauseBtn.classList.remove('next-stage-btn');
                pauseBtn.classList.add('pause-execution');
                // 继续执行
                executeNextStage();
            }
        }
        
        // 重置构建过程
        function resetBuildProcess() {
            currentPipelineId = null;
            autoExecution = true;
            autoExecutionPaused = false;
            const pauseBtn = document.getElementById('pause-btn');
            pauseBtn.textContent = '暂停自动执行';
            pauseBtn.classList.remove('next-stage-btn');
            pauseBtn.classList.add('pause-execution');
            resetBuildDisplay();
            document.getElementById('result').style.display = 'none';
            document.getElementById('log-container').style.display = 'none';
        }
        
        function showMessage(message, type) {
            const resultDiv = document.getElementById('result');
            resultDiv.innerHTML = message;
            resultDiv.className = 'result ' + type;
            resultDiv.style.display = 'block';
            
            // 如果是错误信息，滚动到结果区域
            if (type === 'error') {
                resultDiv.scrollIntoView({ behavior: 'smooth' });
            }
        }
        
        function showLogs(logs) {
            const logContainer = document.getElementById('log-container');
            logContainer.innerHTML = logs.join('<br>');
            logContainer.style.display = 'block';
            logContainer.scrollTop = logContainer.scrollHeight;
        }
        
        // 初始化流水线显示
        function initPipelineDisplay(stageCount) {
            const pipelineStages = document.getElementById('pipeline-stages');
            pipelineStages.innerHTML = '';
            
            // 为每个阶段创建显示元素
            for (let i = 1; i <= stageCount; i++) {
                const stage = document.createElement('div');
                stage.className = 'stage pending';
                stage.id = `stage-${i}`;
                stage.innerHTML = `
                    <div class="stage-icon">${i}</div>
                    <div class="stage-name">阶段 ${i}</div>
                `;
                pipelineStages.appendChild(stage);
            }
        }
        
        // 更新阶段显示
        function updateStageDisplay(stageInfo) {
            const stage = document.getElementById(`stage-${stageInfo.index + 1}`);
            if (stage) {
                stage.className = `stage ${stageInfo.status}`;
            }
        }
        
        // 重置构建显示
        function resetBuildDisplay() {
            document.getElementById('pipeline-stages').classList.add('hidden');
            document.getElementById('stage-detail').classList.add('hidden');
        }
    </script>
</body>
</html>